package com.cloud.drore.eboss.supplier.service.impl;

import com.cloud.drore.eboos.common.base.BaseServiceImpl;
import com.cloud.drore.eboos.common.base.MyMapper;
import com.cloud.drore.eboos.common.base.ResultMessage;
import com.cloud.drore.eboos.common.util.DateToStringUtil;
import com.cloud.drore.eboos.common.util.LocalDateAndDateTransformUtil;
import com.cloud.drore.eboos.exception.BusinessException;
import com.cloud.drore.eboss.supplier.entity.Product;
import com.cloud.drore.eboss.supplier.entity.TicketPriceSynchronization;
import com.cloud.drore.eboss.supplier.entity.TicketSynchronization;
import com.cloud.drore.eboss.supplier.entity.po.GetProductByOTAResponsePo;
import com.cloud.drore.eboss.supplier.entity.po.ProductInfoResponsePo;
import com.cloud.drore.eboss.supplier.entity.vo.ProductForFeeAndRefundFeeVo;
import com.cloud.drore.eboss.supplier.mapper.ProductMapper;
import com.cloud.drore.eboss.supplier.mapper.ProductPriceSynchronizationMapper;
import com.cloud.drore.eboss.supplier.mapper.ProductSynchronizationMapper;

import com.cloud.drore.eboss.supplier.service.IProductSynchronizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;


/**
 * 浙江卓锐科技股份有限公司 版权所有  Copyright 2018<br>
 *
 * @Description: <br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/3/11 9:58 <br>
 * @Author: <a href="410508961@qq.com">夏凯</a>
 */
@Service
@Slf4j
public class ProductSynchronizationImpl extends BaseServiceImpl implements IProductSynchronizationService {


    @Resource
    ProductSynchronizationMapper productSynchronizationMapper;
    @Resource
    ProductMapper productMapper;
    @Resource
    ProductPriceSynchronizationMapper productPriceSynchronizationMapper;
    @Override
    public MyMapper getMapper() {
        return productSynchronizationMapper;
    }


    /**
     * @param productId
     * @param productTotalPrice
     * @param playDate
     * @ClassName: ProductSynchronizationImpl
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage<com.cloud.drore.eboss.supplier.entity.vo.ProductForFeeAndRefundFeeVo>
     * @Decription: 通过游玩时间，总金额，公共产品id，产品类型 获得费率和退款手续费
     * @CreateDate: Created in 2018/3/17 0017 上午 10:27
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<ProductForFeeAndRefundFeeVo> getFeeAndRefundFee(Long productId, BigDecimal productTotalPrice, Date playDate, String productType) throws BusinessException {
        ProductForFeeAndRefundFeeVo productForFeeAndRefundFeeVo = new ProductForFeeAndRefundFeeVo();
        switch (productType) {
            //门票产品
            case "TICKET_PRODUCT":
                ProductForFeeAndRefundFeeVo productForFeeAndRefundFeeTicket = productMapper.queryTicketInfo(productId);
                //将code传出去
                productForFeeAndRefundFeeVo.setProductCode(productForFeeAndRefundFeeTicket.getProductCode());
                /*if(null==productForFeeAndRefundFeeTicket.getCanRefund()||"".equals(productForFeeAndRefundFeeTicket.getCanRefund())){
                    throw new RuntimeException("产品添加数据字段can_refund缺失！");
                }*/
                if (productForFeeAndRefundFeeTicket.getRefundModel().equals("AVAILABLE_FOR_NO_CONSUMPTION")) {
                    //拿到手续费，费率
                    ProductForFeeAndRefundFeeVo productForFeeAndRefundFee = judgeOrderRefundFee(productForFeeAndRefundFeeTicket, productForFeeAndRefundFeeVo, productTotalPrice, playDate);
                    return ResultMessage.success(productForFeeAndRefundFee);
                } else {
                    //不能退款返回-1
                    productForFeeAndRefundFeeVo.setProductRefundWhether("-1");
                    return ResultMessage.success(productForFeeAndRefundFeeVo);
                }
                //组合产品
            case "COMBINATION_PRODUCT":
                ProductForFeeAndRefundFeeVo productForFeeAndRefundFeeProduct = productMapper.queryProductCombinationInfo(productId);
                //将code传出去
                productForFeeAndRefundFeeVo.setProductCode(productForFeeAndRefundFeeProduct.getProductCode());
                if (productForFeeAndRefundFeeProduct.getRefundModel().equals("AVAILABLE_FOR_NO_CONSUMPTION")) {
                    //拿到手续费，费率
                    ProductForFeeAndRefundFeeVo productForFeeAndRefundFee = judgeOrderRefundFee(productForFeeAndRefundFeeProduct, productForFeeAndRefundFeeVo, productTotalPrice, playDate);
                    return new ResultMessage(productForFeeAndRefundFee);
                } else {
                    //不能退款返回-1
                    productForFeeAndRefundFeeVo.setProductRefundWhether("-1");
                    return ResultMessage.success(productForFeeAndRefundFeeVo);
                }
            default:
                throw new BusinessException("没有当前产品类型！");
        }
    }


    /**
     * @param productForFeeAndRefundFee
     * @param productForFeeAndRefundFeeVo
     * @param productTotalPrice
     * @param playDate
     * @ClassName: ProductSynchronizationImpl
     * @Return: com.cloud.drore.eboss.supplier.entity.vo.ProductForFeeAndRefundFeeVo
     * @Decription: 得到退款手续费和退款费率：0是退款不收手续费 -1是不接受退款
     * @CreateDate: Created in 2018/3/17 0017 下午 4:18
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ProductForFeeAndRefundFeeVo judgeOrderRefundFee(ProductForFeeAndRefundFeeVo productForFeeAndRefundFee, ProductForFeeAndRefundFeeVo productForFeeAndRefundFeeVo, BigDecimal productTotalPrice, Date playDate) throws BusinessException {

        switch (productForFeeAndRefundFee.getRefundFee()) {
            //refundRate:不收取手续费
            case "NO_CHARGES":
                productForFeeAndRefundFeeVo.setRefundRate(new BigDecimal("0"));
                productForFeeAndRefundFeeVo.setRefundTotalFee(new BigDecimal("0"));
                return productForFeeAndRefundFeeVo;
            //refundRate:固定费率
            case "FIXED_RATE":
                productForFeeAndRefundFeeVo.setRefundRate(productForFeeAndRefundFee.getFixedRate());
                productForFeeAndRefundFeeVo.setRefundTotalFee(productForFeeAndRefundFee.getFixedRate().multiply(productTotalPrice).divide(new BigDecimal("100")));
                return productForFeeAndRefundFeeVo;
            //refundRate:分时段费率
            case "TIME_INTERVAL_RATE":
                LocalDate currentDate = LocalDate.now();
                //入园日期和退款日期的时间差
                long between = ChronoUnit.DAYS.between(currentDate, LocalDateAndDateTransformUtil.dateToLocalDate(playDate));
                if (between == 1) {
                    BigDecimal refundOneDayAgo = productForFeeAndRefundFee.getRefundOneDayAgo();
                    productForFeeAndRefundFeeVo.setRefundRate(refundOneDayAgo);
                    productForFeeAndRefundFeeVo.setRefundTotalFee(refundOneDayAgo.multiply(productTotalPrice).divide(new BigDecimal("100")));
                } else if (between == 2) {
                    BigDecimal refundTwoDayAgo = productForFeeAndRefundFee.getRefundTwoDaysAgo();
                    productForFeeAndRefundFeeVo.setRefundRate(refundTwoDayAgo);
                    productForFeeAndRefundFeeVo.setRefundTotalFee(refundTwoDayAgo.multiply(productTotalPrice).divide(new BigDecimal("100")));
                } else if (between >= 3) {
                    BigDecimal refundThreeDayAgo = productForFeeAndRefundFee.getRefundThreeDaysAgo();
                    productForFeeAndRefundFeeVo.setRefundRate(refundThreeDayAgo);
                    productForFeeAndRefundFeeVo.setRefundTotalFee(refundThreeDayAgo.multiply(productTotalPrice).divide(new BigDecimal("100")));
                } else {
                    throw new BusinessException("获取退款手续费异常！");
                }
                return productForFeeAndRefundFeeVo;
            default:
                throw new BusinessException("获取退款手续费异常！");
        }
    }

    @Override
    /**
     * @ClassName: ProductSynchronizationImpl
     * @param getProductByOTAResponsePo
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 拿到畅游通上传过来的信息进行同步操作
     * @CreateDate: Created in 2018/3/15 0015 上午 9:56
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    @Transactional
    public ResultMessage insertIntoProductInfoList(GetProductByOTAResponsePo getProductByOTAResponsePo) {
        try {
            //拿到畅游通的对象数列
            List<ProductInfoResponsePo> productInfos = getProductByOTAResponsePo.getProductInfos();

            //查询公共产品表的所有code的列表
            List<Product> totalProductList = productMapper.queryProductListForCode();
            //建立封装存放产品集合的hashmap
            Map<String, String> productHashMap = new HashMap<>();
            for (Product product : totalProductList) {
                productHashMap.put(product.getProductCode(), product.getId().toString());
            }


            //建立用于新增的集合
            List<ProductInfoResponsePo> insertProductList = new ArrayList<>();
            //建立用于修改的集合
            List<ProductInfoResponsePo> updateProductList = new ArrayList<>();
            //判断畅游通里面的数据是应该修改还是新增
            for (ProductInfoResponsePo productInfoResponse : productInfos) {
                String codeFlag = productHashMap.get(productInfoResponse.getProductCode());
                if (null == codeFlag || "".equals(codeFlag)) {
                    insertProductList.add(productInfoResponse);
                } else {
                    if (productInfoResponse.getBookPersonType().equals("CONTACT_PERSON_AND_VISIT_PERSON") && productInfoResponse.getVisitPersonRequiredForQuantity() == 1) {
                        //实名制
                        productInfoResponse.setIsRealName(1);
                    } else {
                        productInfoResponse.setIsRealName(0);
                    }
                    updateProductList.add(productInfoResponse);
                }

            }
            if (updateProductList.size() > 0) {
                //业务分两头，产品编号相同则进行修改操作，不同的话则进行更新操作
                /** 以下是修改操作 */
                Collection c = updateProductList;
                //修改公共产品
                productMapper.updateProductAll(c);
                //修改门票
                productMapper.updateTicketAll(c);
                //修改门票价格信息
                productMapper.updateTicketPrice(c);
           /* productMapper.updateTicket(JSON.toJSONString(updateProductList));
            productMapper.updateProduct(JSON.toJSONString(updateProductList));*/
            }
          /*  if (insertProductList.size() > 0) {
                *//** 以下是新增操作 *//*
                List<Product> listProduct = new ArrayList();
                //插入公共产品信息
                insertIntoCombination(listProduct, insertProductList);
                //蒙哥凯特因需求目前只做修改操作，将插入影藏
                productMapper.insertList(listProduct);
                List<TicketSynchronization> listTicket = new ArrayList();
                List<TicketPriceSynchronization> listTicketPrice = new ArrayList();
                //插入门票信息
                insertIntoTicket(listTicket, insertProductList,listTicketPrice);
                //查询最新插入的公共产品的id
                List<Product> products = productMapper.queryProductList(listProduct.size());
                //将添加好的公共产品表的id放入listTicket
                for (TicketSynchronization ticket : listTicket) {
                    for (Product product : products) {
                        if (product.getProductCode().equals(ticket.getProductCode())) {
                            ticket.setCommonProductId(product.getId());
                        }
                    }
                }

                //批量插入门票信息蒙哥凯特
                productSynchronizationMapper.insertList(listTicket);

                //查询最新插入的门票信息
                List<TicketPriceSynchronization> tickets = productMapper.queryTicketList(listTicketPrice.size());
                //将添加好的门票产品表的id放入listTicketPrice
                for (TicketPriceSynchronization ticket : listTicketPrice) {
                    for (TicketPriceSynchronization ticketPrice : tickets) {
                        if (ticketPrice.getProductCode().equals(ticket.getProductCode())) {
                            ticket.setTicketId(ticketPrice.getId());
                        }
                    }
                }
                //批量插入门票价格信息蒙哥凯特
                productPriceSynchronizationMapper.insertList(listTicketPrice);

            }*/
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException("畅游通产品同步失败！" + e);
        }

        return ResultMessage.success("success");
    }

    /**
     * @param list
     * @param productInfos
     * @ClassName: ProductSynchronizationImpl
     * @Return: void
     * @Decription: 拿到畅游通上传过来的信息进行同步操作(插入门票信息)
     * @CreateDate: Created in 2018/3/15 0015 上午 10:04
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public void insertIntoTicket(List list, List<ProductInfoResponsePo> productInfos,List<TicketPriceSynchronization> listTicketPrice) {
        productInfos.stream().forEach(productInfoResponsePo -> {
            TicketSynchronization ticket = new TicketSynchronization();
            /** 供应商的结算价*/
            TicketPriceSynchronization ticketPrice = new TicketPriceSynchronization();
            ticketPrice.setSalesPrice(productInfoResponsePo.getCalendarPrices().get(0).getMarketPrice());
            ticketPrice.setSettlementPrice(productInfoResponsePo.getCalendarPrices().get(0).getSupplierSettlementPrice());
            ticketPrice.setProductCode(productInfoResponsePo.getProductCode());
            listTicketPrice.add(ticketPrice);
            /** 产品编号  产品代码*/
            ticket.setProductCode(productInfoResponsePo.getProductCode());
            /** 目的地(畅游通) */
            ticket.setCity(productInfoResponsePo.getCity());
            /**  产品名称 门票名称*/
            ticket.setName(productInfoResponsePo.getProductName());
            /** 支付类型 */
            ticket.setPaymentType(productInfoResponsePo.getPaymentType());
            /** 提前预定天数(畅游通) */
            ticket.setBookAdvanceDay(productInfoResponsePo.getBookAdvanceDay());
            /** 提前预定时间(畅游通) 需要将string转化为Date*/
            ticket.setBookAdvanceTime(DateToStringUtil.getTimeShort(productInfoResponsePo.getBookAdvanceTime()));
            /** 预定后几小时入园(畅游通) */
            ticket.setUseAdvanceHour(productInfoResponsePo.getUseAdvanceHour());
            /** 不支付自动取消时间(畅游通) */
            ticket.setDaysAfterUseDateValid(productInfoResponsePo.getDaysAfterUseDateValid());
            /** 是否需要游客信息(畅游通) */
            ticket.setBookPersonType(productInfoResponsePo.getBookPersonType());
            /** 每几个游客共享一个游客信息(畅游通) */
            ticket.setVisitPersonRequiredForQuantity(productInfoResponsePo.getVisitPersonRequiredForQuantity());
            /**有效期限制(畅游通)*/
            ticket.setValidType(productInfoResponsePo.getValidType());
            /** 不支付自动取消时间(畅游通) */
            ticket.setAutoCancelTime(productInfoResponsePo.getAutoCancelTime());
            /** 使用说明 */
            ticket.setInstruction(productInfoResponsePo.getInstruction());
            /** 是否支持退款(畅游通) */
            ticket.setCanRefund(productInfoResponsePo.getCanRefund());

            /** 是否支持退款(运营商自己的判断)refund_model */
            ticket.setRefundModel(productInfoResponsePo.getCanRefund().equals("TRUE") ? "AVAILABLE_FOR_NO_CONSUMPTION" : "NOT_REFUNDABLE");


            /** 是否支持过去退款(畅游通) */
            ticket.setCanOverdueRefund(productInfoResponsePo.getCanOverdueRefund());
            /** 最晚有效期前几天几点可退款(畅游通) */
            ticket.setRefundApplyTimeBeforeValidEndDay(productInfoResponsePo.getRefundApplyTimeBeforeValidEndDay());
            /** 退款手续费类型(畅游通) */
            ticket.setRefundChargeType(productInfoResponsePo.getRefundChargeType());
            /** 退款规则(畅游通) */
            ticket.setRefundInfo(productInfoResponsePo.getRefundInfo());
            /** 短信模板(畅游通) */
            ticket.setSmsTemplet(productInfoResponsePo.getSmsTemplet());
            /** 电子票类型(畅游通) */
            ticket.setETicketType(productInfoResponsePo.getETicketType());
            /** 是否实名制(畅游通) */
            if (productInfoResponsePo.getBookPersonType().equals("CONTACT_PERSON_AND_VISIT_PERSON") && productInfoResponsePo.getVisitPersonRequiredForQuantity() == 1) {
                ticket.setIsRealName(1);
            }
            list.add(ticket);
        });
    }

    /**
     * @param list
     * @param productInfos
     * @ClassName: ProductSynchronizationImpl
     * @Return: void
     * @Decription: 拿到畅游通上传过来的信息进行同步操作(公共产品信息)
     * @CreateDate: Created in 2018/3/15 0015 上午 10:09
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public void insertIntoCombination(List list, List<ProductInfoResponsePo> productInfos) {
        productInfos.stream().forEach(productInfoResponsePo -> {
            Product product = new Product();
            /** 供应商的结算价*/
            product.setSupplierSettlementPrice(productInfoResponsePo.getCalendarPrices().get(0).getSupplierSettlementPrice());
            /**  产品名称 门票名称*/
            product.setProductName(productInfoResponsePo.getProductName());
            /** 支付类型 */
            product.setPaymentType(productInfoResponsePo.getPaymentType());
            /** 使用说明 */
            product.setInstruction(productInfoResponsePo.getInstruction());
            /** 是否支持退款(畅游通) */
            product.setRefundModel(productInfoResponsePo.getCanRefund().equals("TRUE") ? "AVAILABLE_FOR_NO_CONSUMPTION" : "NOT_REFUNDABLE");

            /** 是否实名制(畅游通) */
            if (productInfoResponsePo.getBookPersonType().equals("CONTACT_PERSON_AND_VISIT_PERSON") && productInfoResponsePo.getVisitPersonRequiredForQuantity() == 1) {
                product.setIsRealName(1);
            }
            //产品代码用于识别id的唯一性
            product.setProductCode(productInfoResponsePo.getProductCode());
            //产品类新（都是单产品）
            product.setProductType("TICKET_PRODUCT");
            list.add(product);
        });
    }
}